#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <ctype.h>
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include "Table.H"
#include "Player.H"


using namespace std;

void *PrintHello(void *player)
{
    Player *pPlayer = reinterpret_cast<Player*>( player);
    cout << "Hello World! Player name and id=  " << pPlayer->GetName() << " Id= " << pPlayer->GetPlayerId() << endl;
    cout << "MY next player details =  " << pPlayer->GetNextPlayer()->GetName() << " Id= " << pPlayer->GetNextPlayer()->GetPlayerId() << endl;
    pPlayer->Play();
    pthread_exit(NULL);
}

int main ( int argc, char *argv[] )
{
    int num_players=argc;
    cout << "Total number of players = ";
    //cin >> num_players;
    cout << cin.fail() << std::endl;
    if ( cin.fail() != 0 || num_players > 4 || num_players < 2 || num_players == 3 ) return 0;

    Table *pGameTable = new Table ( num_players ) ;

    Player *p[4];

    char player_name[ 100 ];
    for ( int i = 0; i < num_players ; i++ )    
    {
        if ( 0 == i)
            std::cout << "Enter your Name:        " ;
        else
            std::cout << "Enter next player's name: " ;
        cin >> player_name;
        p[i] = new Player( i, player_name );

    }

    for ( int i = 0; i < num_players ; i++ )
    {
        pGameTable->RegisterPlayer( p[i] );
        p[i]->SetNextPlayer( p[ (i+1)%num_players ] );
    }

    pthread_t threads[num_players];

    int rc;
    int i;
    for( i=0; i < num_players; i++ )
    {
        cout << "main() : creating thread, " << i << endl;
        rc = pthread_create(&threads[i], NULL, PrintHello, (void *)p[i]);
        if (rc){
            cout << "Error:unable to create thread," << rc << endl;
            exit(-1);
        }
    }
    //Event e;
    //pGameTable->Notify(&e);
	//sleep (6);
    pGameTable->Start( p[0] );
    pthread_exit(NULL);
}
